<template>
  <!-- 提货单创建 -->
  <div class="createOrder_styl" v-if="modalShow">
    <Modal
      ref="modalEle"
      v-model="modalShow"
      :mask-closable="false"
      width="900"
      class="modal-styl"
    >
      <p slot="header" style="text-align: center">
        <span>创建提货单</span>
      </p>
      <Form
        ref="editForm"
        label-position="right"
        :label-width="85"
        :model="skuData"
      >
        <Row :gutter="24" align="middle">
          <Col span="9">
            <FormItem
              :label="createType == 'order' ? '订单名称:' : '合同名称:'"
              prop="name"
            >
              {{ skuData.name }}
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem
              :label="createType == 'order' ? '订单编码:' : '合同编码:'"
              prop="code"
            >
              {{ skuData.code }}
            </FormItem>
          </Col>
          <Col span="7">
            <FormItem
              :label="createType == 'order' ? '订单类型:' : '合同类型:'"
            >
              普通订单
            </FormItem>
          </Col>
        </Row>
        <Row :gutter="24">
          <Col span="9">
            <FormItem label="规格名称:" prop="productAttrName">
              {{ skuData.productAttrName }}
            </FormItem>
          </Col>
          <Col span="8">
              <FormItem label="销售公司:" prop="companyName">
                {{ skuData.companyName }}
              </FormItem>
            </Col>
            <Col span="7">
              <FormItem label="业务经理:" prop="personName">
                {{ skuData.personName }}
              </FormItem>
            </Col>
          <!-- <Col span="8">
            <FormItem label="可用余额:" prop="companyCode">
              {{ nowAmount }} 元
            </FormItem>
          </Col> -->
          <!-- <Col span="8" class="action_styl">
            <a @click="collapse = !collapse">
              <template v-if="!collapse">
                展开
                <Icon type="ios-arrow-down" />
              </template>
              <template v-else>
                收起
                <Icon type="ios-arrow-up" />
              </template>
            </a>
          </Col> -->
          
        </Row>
        <!-- <template v-if="collapse"> -->
          <Row :gutter="24">
          <Col span="9">
            <FormItem label="规格单价:" prop="nprice">
              {{ skuData.nprice }}元
            </FormItem>
          </Col>
          <Col span="8">
            <FormItem
              :label="createType == 'order' ? '订单余量:' : '合同余量:'"
              prop="billNum"
            >
              {{ skuData.billNum }}吨
            </FormItem>
          </Col>
          <Col span="7" class="action_styl">
            <FormItem prop="companyCode" class="change_styl">
              <div class="buttonStyle">
                <Button
                  icon="md-add"
                  type="success"
                  size="small"
                  @click="showTextarea = true"
                  >快速添加</Button
                >
              </div>
            </FormItem>
            <Button style="margin: 0 10px"   size="small">
              <a class="a_styl" :href="downUrl" download="车辆信息模板"
                >下载模板</a
              >
            </Button>
            <Upload
              :action="upUrl"
              :show-upload-list="false"
              :on-success="updataFastAddCarsFun"
            
            >
              <Button icon="ios-cloud-upload-outline" type="primary"   size="small"
                >上传车辆信息</Button
              >
            </Upload>
          </Col>
          <!-- <Col span="9">
              <FormItem label="已下单量:" prop="billNum">
                {{ itemCopy.billNum }}
              </FormItem>
            </Col> -->
        </Row>
        <!-- </template> -->
        
        <Row :gutter="24">
          
          <Col span="8" class="action_styl">
            
          </Col>
          
          <Col span="8" class="action_styl">
            
          </Col>
         
        </Row>
      </Form>
      <Table
        :data="tableData"
        :columns="columns"
        height="400"
        sum-text="合计"
        :summary-method="handleSummary"
        show-summary
      >
        <template slot-scope="{ row, index }" slot="driverName">
          <Input
            type="text"
            placeholder="司机姓名"
            v-model="tableData[index].driverName"
          ></Input>
        </template>
        <template slot-scope="{ row, index }" slot="driverCard">
          <Input
            type="text"
            placeholder="身份证号"
            v-model="tableData[index].driverCard"
          ></Input>
        </template>
        <template slot-scope="{ row, index }" slot="nnum">
          <Input
            type="text"
            placeholder="数量"
            v-model="tableData[index].nnum"
          ></Input>
        </template>
        <template slot-scope="{ row, index }" slot="driverPhone">
          <Input
            type="text"
            placeholder="手机号码"
            v-model="tableData[index].driverPhone"
          ></Input>
        </template>
        <template slot-scope="{ row, index }" slot="carNumber">
          <Input
            type="text"
            search
            placeholder="车牌号"
            v-model="tableData[index].carNumber"
            @on-search="searchcarFun(index)"
          ></Input>
        </template>
        <template slot-scope="{ row, index }" slot="action">
          <Button @click="delBillItem(index)" type="error" ghost>删除</Button>
        </template>
      </Table>

      <div slot="footer" class="foot_styl">
        <Button icon="md-add" type="text" @click="addBillItem">添加车辆</Button>
        <div class="">
          <Button type="text" @click="modalShow = false">取消</Button>
          <Button type="primary" :loading="btnLoading" @click="submitOrderFun"
            >保存</Button
          >
        </div>
      </div>
    </Modal>

    <!-- 快速添加 -->
    <div v-if="showTextarea">
      <Modal
        v-model="showTextarea"
        title="车辆信息"
        footer-hide
        :width="500"
        :mask-closable="false"
      >
        <p slot="header" style="text-align: center">
          <span>车辆信息</span>
        </p>
        <Input
          ref="textarea1"
          id="textarea1"
          v-model="textContent"
          type="textarea"
          :rows="20"
          :placeholder="placeholder"
        />

        <div style="text-align: right; margin-top: 20px">
          <Button
            type="text"
            style="margin-right: 8px"
            @click="showTextarea = flase"
            >取消</Button
          >
          <Button type="primary" @click="submitCarsFun" :loading="btnLoading"
            >保存</Button
          >
        </div>
      </Modal>
    </div>
    <!-- 车牌号选择 -->
    <QdSelectCar ref="QdSelectCar" @changeValue="changeValue"></QdSelectCar>
  </div>
</template>

<script>
import { mapGetters, mapMutations } from "vuex";
import {
  validateCarNoFun,
  validatePhoneFun,
  validateIdCardFun,
} from "@/tool/myValidator";
import QdSelectCar from "@/components/common/Qd-SelectCar";
import Setting from "@/setting.env";

export default {
  components: { QdSelectCar },
  props: {
    createType: {
      type: String,
      default: "",
    }, // 根据传入不同的类型 区分 合同（contract）下单还是订单（order）下单
  },
  data() {
    return {
      downUrl: Setting.templateUrl + "/guns/sysFileInfo/publicDownload?fileId=1733056903713468418",
      upUrl: Setting.templateUrl + "/qd-s-system/importbilltemplte",
      skuData: {},
      collapse: false,
      nowAmount: 0,
      selectIndex: -1,
      showTextarea: false,
      btnLoading: false,
      textContent: "",
      placeholder:
        "例如：\n鲁E88888\n张三\n370503200101010011\n17853486666\n30\n\n鲁E66666\n李四\n370503200101010011\n17853486666\n30",
      tableData: [],
      modalShow: false,
      columns: [
        {
          title: "车牌号",
          slot: "carNumber",
          key: "carNumber",
          minWidth: 133,
          align: "center",
        },
        {
          title: "司机姓名",
          slot: "driverName",
          key: "driverName",
          minWidth: 100,
          align: "center",
        },
        {
          title: "身份证号",
          slot: "driverCard",
          key: "driverCard",
          minWidth: 190,
          align: "center",
        },
        {
          title: "手机号码",
          slot: "driverPhone",
          key: "driverPhone",
          minWidth: 140,
          align: "center",
        },
        {
          title: "数量",
          slot: "nnum",
          key: "nnum",
          minWidth: 80,
          align: "center",
        },
        // {
        //   title: "排放标准",
        //   slot: "carType",
        //   key: "carType",
        //   minWidth: 90,
        //   align: "center"
        // },
        {
          title: "操作",
          slot: "action",
          align: "center",
          width: 90,
        },
      ],
    };
  },
  computed: {
    ...mapGetters(["store_userInfo", "store_goodsInfo"]),
  },
  mounted() {},
  methods: {
    ...mapMutations(["set_goodsInfo"]),

    // 选择车辆信息
    changeValue(val) {
      this.$set(this.tableData, [this.selectIndex], {
        ...this.tableData[this.selectIndex],
        ...{
          carNumber: val[0].carNo,
          driverName: val[0].driverName,
          driverCard: val[0].driverCard,
          driverPhone: val[0].driverPhone,
          nnum: "20",
          //   carType: '3',
        },
      });
      val.splice(0, 1);
      let valCopy = val.map((item) => {
        return {
          carNumber: item.carNo,
          driverName: item.driverName,
          driverCard: item.driverCard,
          driverPhone: item.driverPhone,
          //   carType: '3',
          nnum: "20",
        };
      });
      this.tableData.splice(this.selectIndex + 1, 0, ...valCopy);
      //   console.log('tableDatatableData', this.tableData);
    },
    
    // 上传添加 车辆 成功
    updataFastAddCarsFun(res) {
      console.log(res);
      let tableData = res.data;
      tableData.forEach((item, index) => {
        tableData[index] = {
          carNumber: item.carNumber,
          driverName: item.carName,
          driverCard: item.carCard,
          driverPhone: item.phone,
          nnum: +item.num,
        };
      });
      this.tableData.push(...res.data);
      this.$Message.success("上传文件成功");
    },
    openFun(skuData) {
      console.log("1111111111111",skuData);
      this.tableData = [];
      this.skuData = {}
      this.skuData = {
        ...skuData
      }
      this.modalShow = true;
    },
    // 提交订单信息
    submitOrderFun() {
      //   console.log("skuInfoskuInfo数据---------", this.skuInfo);
      if (!this.tableData.length) {
        return this.$Message.error("请添加车辆!");
      }

      let error = {
        index: "",
        title: "",
      };
      let flag = this.tableData.some((item, index) => {
        if (!validateCarNoFun(item.carNumber)) {
          error = {
            index,
            title: "车牌号",
          };
          return true;
        }
        if (!item.driverName) {
          error = {
            index,
            title: "司机姓名",
          };
          return true;
        }
        if (!validateIdCardFun(item.driverCard)) {
          error = {
            index,
            title: "身份证号",
          };
          return true;
        }
        if (!validatePhoneFun(item.driverPhone)) {
          error = {
            index,
            title: "手机号码",
          };
          return true;
        }
        if (!item.nnum) {
          error = {
            index,
            title: "数量",
          };
          return true;
        }
      });

      if (flag) {
        return this.$Message.error(
          `请完善第&nbsp;${error.index + 1}&nbsp;条${error.title}!`
        );
      }

      // let data = this.tableData.map((item) => {
      //   let itemCopy = {
      //     ...this.skuInfo,
      //     ...item,
      //     orderIs: "0",
      //   };
      //   delete itemCopy.id;
      //   return itemCopy;
      // });
      console.log(this.skuData);

      // return
      let data = {
        ...this.skuData,
        carList: this.tableData,
        method: this.createType == "order" ? 2 : 1,
        id: "",
      };
      if (this.createType == "order") {
        data.orderId = this.skuData.id;
      } else {
        data.contractId = this.skuData.id;
      }
      this.btnLoading = true;
      this.httpPost(this.API.API_addOrder, data)
        .then((res) => {
          // this.$emit("addOrderSuccess");
          this.$Message.success("下单成功！");
          this.btnLoading = false;
          this.modalShow = false;

          // let flag = this.store_goodsInfo.some(
          //   (item) => item.storeNameId == this.skuInfo.storeName
          // );
          // if (!flag) {
          //   let goodsInfo = [
          //     {
          //       storeName: this.skuInfo.storeName,
          //       storeNameId: this.skuInfo.storeNameId,
          //     },
          //     ...this.store_goodsInfo,
          //   ];

          //   goodsInfo.length > 10 ? (goodsInfo.length = 10) : "";
          //   this.set_goodsInfo(goodsInfo);
          // }

          // this.$router.push({
          //   path: "/personalCenter/billOrder",
          // });

        })
        .catch((err) => {
          console.error("创建提货单报错:", err);

          if (err.toString().indexOf("商品单价变动") > -1) {
            this.$Modal.confirm({
              title: "确认",
              content: err.toString().replace(/Error/, "提示") + "?",
              onOk: () => {
                data.forEach((item, index) => {
                  item.amountStatus = "1";
                });
                this.httpPost(this.API.API_addOrder, data)
                  .then((res) => {
                    this.$emit("addOrderSuccess");
                    this.$Message.success("下单成功！");
                    this.btnLoading = false;
                    this.modalShow = false;
                    // 跳转订单列表
                    this.$router.push({
                      path: "/personalCenter/billOrder",
                    });
                  })
                  .catch((err) => {
                    console.log(errs);
                  });
              },
              onCancel: () => {
                this.btnLoading = false;
              },
            });
          } else {
            this.btnLoading = false;
          }
        });
    },
    // 获取可用余额
    getUserMoneyFun(companyCode) {
      let data = {
        companyCode: companyCode,
        customerId: this.store_userInfo.id,
      };
      this.httpPost(this.API.API_moneyHead, data)
        .then((res) => {
          if (res.success) {
            if (res.data.length > 0) {
              this.nowAmount = res.data[0].nowAmount;
            }
          }
        })
        .catch((err) => {
          console.error(err);
        });
    },
    // 搜索车辆信息
    searchcarFun(index) {
      this.selectIndex = index;
      this.$refs.QdSelectCar.openFun();
    },
    // 快速添加保存
    submitCarsFun() {
      let a = JSON.stringify(this.$refs.textarea1.currentValue);
      let b = a.replace(/\\n\\n/g, "/qdkj/");

      this.httpPost(this.API.API_checktwo, {
        checkInfo: b,
      }).then((res) => {
        if (res.code == "200") {
          this.tableData = res.data;
          this.showTextarea = false;
        } else {
          this.$Message.error(res.message);
        }
      });
    },
    // 添加车辆
    addBillItem() {
      this.tableData.push({
        carNumber: "",
        driverName: "",
        driverCard: "",
        driverPhone: "",
        // carType: "",
        nnum: 20,
      });
    },
    // 删除车辆
    delBillItem(idx) {
      this.tableData.splice(idx, 1);
    },
    //处理合计的列表
    handleSummary({ columns, data }) {
      const sums = {};
      columns.forEach((column, index) => {
        const key = column.key;
        if (index === 0) {
          sums[key] = {
            key,
            value: data.length + " 辆",
          };
          return;
        } else if (index === 4) {
          const values = data.map((item) => Number(item[key]));
          const v = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
          sums[key] = {
            key,
            value: v + " 吨",
          };
        } else {
          sums[key] = {
            key,
            value: "",
          };
          return;
        }
      });
      return sums;
    },
    toPageFun(item, index) {
      this.$router.push(item.path);
    },
  },
};
</script>
<style lang="less" scoped>
@import "~@/assets/styles/main.less";
@deep: ~">>>";
.action_styl {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
::v-deep .ivu-modal-header {
  background-image: url("~@/assets/images/modal_back900.png");
}
.ivu-form-item/deep/ {
  margin-bottom: 0px;
}
.buttonStyle {
  // margin-bottom: 10px;
  text-align: center;
}
.createOrder_styl {
}
.foot_styl {
  .flex-x();
}
</style>
